import cv2
import os
from timecacu import getTimer

# 函数来加载分类器
def load_cascades(classifier_dict):
    cascades = {}
    for friendly_name, filename in classifier_dict.items():
        classifier = cv2.CascadeClassifier(cv2.data.haarcascades + filename)
        if classifier.empty():
            print(f"警告: {filename} ({friendly_name}) 未找到.")
        else:
            cascades[friendly_name] = classifier
    return cascades


# 检测函数，传入灰度图和级联分类器
def detect(img, cascade):
    # 调用级联分类器的人脸检测函数，返回人脸框
    rects = cascade.detectMultiScale(img, scaleFactor=1.1, minNeighbors=3, flags=cv2.CASCADE_SCALE_IMAGE)
    if len(rects) == 0:
        return []
    rects[:,2:] += rects[:,:2]
    return rects

# 在图像上描画出人脸框
def draw_rects(img, rects, color):
    img_copy = img.copy()  # 创建图像的可写副本
    for rect in rects:
        x1, y1, x2, y2 = rect
        cv2.rectangle(img_copy, (x1, y1), (x2, y2), color, 2)
    return img_copy


def cv_findFace(img, classifier, output_path, image_size=160):

    # 将图像转成灰度图，并做直方图均衡化提高图像质量
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    gray = cv2.equalizeHist(gray)

    # 使用级联分类器检测人脸
    rects = detect(gray, classifier)

    faces = []  # 用于存储调整尺寸后的人脸图像

    if len(rects) != 0:
        # 在图像上画出检测到的每张人脸
        for rect in rects:
            x1, y1, x2, y2 = rect
            # 提取人脸区域
            face = img[y1:y2, x1:x2]

            # 使用OpenCV进行图像缩放
            resized_face = cv2.resize(face, (image_size, image_size), interpolation=cv2.INTER_LINEAR)
            faces.append(resized_face)

            # 绘制矩形框
            cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)

        # 保存带有矩形框的图像到指定位置
        cv2.imwrite(output_path, img)

        # 返回检测到的人脸图像列表
        return faces
    else:
        print("未检测到人脸。")
        return []


# 分类器名称及对应的文件名
classifier_dict = {
    'default': 'haarcascade_frontalface_default.xml',
    'quick_Haar': 'haarcascade_frontalface_alt2.xml',
    'tree': 'haarcascade_frontalface_alt_tree.xml',
    'Haar_1': 'haarcascade_frontalface_alt.xml',
}

def captureFaceVideo(video,scale = 1):
    # 加载所有人脸检测器
    face_cascades = load_cascades(classifier_dict)
    cap = cv2.VideoCapture(video)
    classifier = face_cascades['default']
    #cv_findFace(img, classifier, output_path)

    t = getTimer("opencv_rec")

    while True:
        # 读取视频帧
        ret, frame = cap.read()
        # 将图像转成灰度图，并做直方图均衡化提高图像质量
        t.start()
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        gray = cv2.equalizeHist(gray)
        gray = cv2.resize(gray, (0, 0), fx=1.0 / scale, fy=1.0 / scale)
        # 使用级联分类器检测人脸
        rects = detect(gray, classifier)
        t.end()
        if len(rects) != 0:
            # 在图像上画出检测到的每张人脸
            for rect in rects:
                x1, y1, x2, y2 = rect
                cv2.rectangle(frame, (x1*scale, y1*scale), (x2*scale, y2*scale), (0, 255, 0), 2)

        cv2.imshow('Face Detection', frame)
        # 按下q键退出
        if cv2.waitKey(1) == ord('q'):
            break
    t.show()
    # 释放资源
    cap.release()
    cv2.destroyAllWindows()



captureFaceVideo(0, 4)
